((document) => {
    const list = document.getElementById('list')
    const messageInput = document.getElementById('message')
    const sendBtn = document.getElementById('send')

    const ws = new WebSocket('ws:localhost:8000')
    let username = ''

    const init = () => {
        bindEvent()
    }
    function bindEvent(){
        sendBtn.addEventListener('click', handleSendBtnClick, false)
        ws.addEventListener('open', handleOpen, false)
        ws.addEventListener('close', handleClose, false)
        ws.addEventListener('error', handleError, false)
        ws.addEventListener('message', handleMessage, false)
    }
    function handleSendBtnClick(){
        const msg = messageInput.value.trim()
        if(!msg.length){
            return
        }
        console.log('click',username);
        ws.send(JSON.stringify({
            username,
            msg,
            dataTime : new Date().getTime()
        }))
        messageInput.value = ''
    }
    function handleOpen(e){
        console.log('open');
        username = localStorage.getItem('username')
        if(!username){
            location.href = 'entry.html'
        }
    }
    function handleClose(e){
        console.log('close');
    }
    function handleError(e){
        console.log('error');
    }
    function handleMessage(e){
        const data = JSON.parse(e.data)
        list.appendChild(createMsg(data))
    }
    function createMsg(data){
        const {username, msg, dataTime} = data
        const item = document.createElement('li')
        item.innerHTML = `
            <p>
                <span>${username}</span>
                <i>${new Date(dataTime)}</i>
            </p>
            <p>消息：${msg}</p>
        `
        return item
    }


    init()
})(document)